package com.common;

import java.awt.Image;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.StringTokenizer;
import javax.imageio.ImageIO;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.struts2.ServletActionContext;
import com.action.BaseAction;
import com.dao.IUserDao;
import com.po.Menu;
import com.po.UserSys;



	public class Tools {		
		//工具
		public static String getDateMonthStr(){
			return (new SimpleDateFormat("yyyy-MM")).format(new Date());
	    }
		public static String getNowRandom() {
			return (new SimpleDateFormat("yyyyMMddHHmmssMS")).format(new Date())+ random(16);
		}
		public static String getNowRandomTwo() {
			return (new SimpleDateFormat("yyyyMMddHHmmssMS")).format(new Date())+ random(2);
		}
		public static String getNowRandomThree() {
			return (new SimpleDateFormat("yyyyMMddHHmmssMS")).format(new Date());
		}
		public static String getCurrentTime() {
			return (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(new Date());
		}
		public static void setVOToVO(Object objVO1, Object objVO2) {
			try {
				BeanUtils.copyProperties(objVO2, objVO1);
			} catch (Exception ex) {
				System.out.println("setVOToVO is Error!!!" + ex.getMessage());
			}
		}
		public static String random(int len) {
			long lng = new Random().nextLong();
			if (lng < 0) {
				lng = lng * (-1);
			}
			String lngStr = "" + lng;
			if (lngStr.length() < len) {
				lngStr += random(len - lngStr.length());
			} else {
				lngStr = lngStr.substring(0, len);
			}
			return lngStr;
		}
		public static String htmlCheck(String str) {
			if (str == null) {
				return null;
			} else {
				String fString = str;
				//fString = fString.replaceAll(";", "&#59;");
				fString = fString.replaceAll("<", "&lt;");
				fString = fString.replaceAll(">", "&gt;");
				fString = fString.replaceAll("\n", "");
				fString = fString.replaceAll("--", "&#45;&#45;");
				fString = fString.replaceAll("'", "&#39;");
				fString = fString.replaceAll("\"", "&#34;");
				//fString = fString.replaceAll("   ", "&nbsp;");
				fString = fString.replaceAll("%", "％");
				fString = fString.replaceAll("'", "‘");
				return fString;
			}
		}

		public static String decode(String str) {
			if (str == null) {
				return null;
			} else {
				String fString = str;
				//fString = fString.replaceAll("&nbsp;", "   ");
				fString = fString.replaceAll("&#34;", "\"");
				fString = fString.replaceAll("&#39;", "'");
				fString = fString.replaceAll("&#45;&#45;", "--");
				fString = fString.replaceAll("<br/>", "\n");
				fString = fString.replaceAll("&gt;", ">");
				fString = fString.replaceAll("&lt;", "<");
				//fString = fString.replaceAll("&#59;", ";");
				fString = fString.replaceAll("%", "％");
				fString = fString.replaceAll("'", "‘");
				return fString;
			}
		}

		public static String decodeSMS(String str) {
			if (str == null) {
				return null;
			} else {
				String fString = str;
				fString = fString.replaceAll("&#34;", "“");
				fString = fString.replaceAll("&#39;", "”");
				fString = fString.replaceAll("&gt;", "＞");
				fString = fString.replaceAll("&lt;", "＜");
				fString = fString.replaceAll("<br/>", "\n");
				return fString;
			}
		}

		public static String decodeAll(String str) {
			if (str == null) {
				return null;
			} else {
				String fString = str;
				fString = fString.replaceAll("&nbsp;", "   ");
				fString = fString.replaceAll("&#34;", "”");
				fString = fString.replaceAll("&#39;", "‘");
				fString = fString.replaceAll("&#45;&#45;", "－－");
				fString = fString.replaceAll("<br/>", "\r\n");
				fString = fString.replaceAll("<BR>", "\r\n");
				fString = fString.replaceAll("<br>", "\r\n");
				fString = fString.replaceAll("&gt;", "＞");
				fString = fString.replaceAll("&lt;", "＜");
				fString = fString.replaceAll("&#59;", "；");
				fString = fString.replaceAll("%", "％");
				fString = fString.replaceAll("'", "‘");
				fString = fString.replaceAll("&#8226;", "\267");
				fString = fString.replaceAll("&#100000001;", "\267");
				fString = fString.replaceAll("&#100000002;", "，");
				fString = fString.replaceAll("&#100000003;", "？");
				fString = fString.replaceAll("&#100000004;", "!");
				fString = fString.replaceAll("&#100000005;", "。");
				fString = fString.replaceAll("&#100000006;", "《");
				fString = fString.replaceAll("&#100000007;", "》");
				fString = fString.replaceAll("&#100000008;", "【");
				fString = fString.replaceAll("&#100000009;", "】");
				fString = fString.replaceAll("&#1000000010;", "—");
				fString = fString.replaceAll("&#1000000011;", "%");
				fString = fString.replaceAll("&#1000000012;", "-");
				fString = fString.replaceAll("&#1000000013;", "…");
				fString = fString.replaceAll("&#1000000014;", "~");
				fString = fString.replaceAll("&#1000000015;", "“");
				fString = fString.replaceAll("&#1000000016;", "”");
				fString = fString.replaceAll("&#1000000017;", "；");
				fString = fString.replaceAll("&#1000000018;", "’");
				fString = fString.replaceAll("&#1000000019;", "‘");
				fString = fString.replaceAll("&#1000000020;", "、");
				fString = fString.replaceAll("&#1000000021;", "/");
				fString = fString.replaceAll("&#1000000022;", "@");
				fString = fString.replaceAll("&#1000000023;", "（");
				fString = fString.replaceAll("&#1000000024;", "）");
				fString = fString.replaceAll("&#1000000025;", "＝");
				fString = fString.replaceAll("&#1000000026;", "＋");
				return fString;
			}
		}
		

		public static String getStringBetween(String src, String beginStr, String endStr) {
			int beginIndex = src.indexOf(beginStr);
			if (beginIndex < 0) {
				return "";
			}
			String leftStr = src.substring(beginIndex + beginStr.length(), src.length());
			int endIndex = leftStr.indexOf(endStr);
			if (endIndex < 0) {
				return "";
			}
			return leftStr.substring(0, endIndex);
		}
		
		public static String getLastStrByLastStr(String src, String str) {
			int i = src.lastIndexOf(str);
			if (i < 0) {
				return "";
			}
			return src.substring(i + str.length());
		}
		public static String getLastStrByFirstStr(String src, String str) {
			int i = src.indexOf(str);
			if (i < 0) {
				return "";
			}
			return src.substring(i + str.length());
		}
		public static String copyFile(String root, String folder, String src) {
			String srcFileName = getLastStrByLastStr(src, "resources");
			if (srcFileName.length() < 1) {
				return "";
			}
			srcFileName="resources"+srcFileName;
			String srcFilePath = getLastStrByLastStr(src, "/");
			if (srcFilePath.length() < 1) {
				return "";
			}
			System.out.println(root + srcFileName);
			System.out.println(root + folder + srcFilePath);
			if (copyFiles(root + srcFileName, root + folder + srcFilePath)) {
				return srcFilePath;
			}
			return "";
		}
		public static boolean copyFiles(String oldPath, String newPath) {
			try {
				System.out.println("oldPath===="+oldPath);
				System.out.println("newPath===="+newPath);
				int bytesum = 0;
				int byteread = 0;
				File oldfile = new File(oldPath);
				if (oldfile.exists()) {
					InputStream inStream = new FileInputStream(oldPath);
					FileOutputStream fs = new FileOutputStream(newPath);
					byte[] buffer = new byte[2048];
					while ((byteread = inStream.read(buffer)) != -1) {
						bytesum += byteread;
						System.out.println(bytesum);
						fs.write(buffer, 0, byteread);
					}
					inStream.close();
					return true;
				} else {
					return false;
				}
			} catch (Exception e) {
				e.printStackTrace();
				return false;
			}
		}
		public static String copyFilesString(String oldPath, String newPath) {
			String newName="";
			try {
				int bytesum = 0;
				int byteread = 0;
				File oldfile = new File(oldPath);
				if (oldfile.exists()) {
					InputStream inStream = new FileInputStream(oldPath);
					FileOutputStream fs = new FileOutputStream(newPath);
					byte[] buffer = new byte[1444];
					while ((byteread = inStream.read(buffer)) != -1) {
						bytesum += byteread;
						fs.write(buffer, 0, byteread);
					}
					inStream.close();
					
					return newName=newPath;
				} else {
					return newName;
				}
			} catch (Exception e) {
				e.printStackTrace();
				return newName;
			}
		}
		public static void delFolder(String folderPath) {
			try {
				delAllFile(folderPath);
				String filePath = folderPath;
				filePath = filePath.toString();
				java.io.File myFilePath = new java.io.File(filePath);
				myFilePath.delete();

			} catch (Exception e) {
				e.printStackTrace();

			}

		}
		public static void delAllFile(String path) {
			File file = new File(path);
			if (!file.exists()) {
				return;
			}
			if (!file.isDirectory()) {
				return;
			}
			String[] tempList = file.list();
			File temp = null;
			for (int i = 0; i < tempList.length; i++) {
				if (path.endsWith(File.separator)) {
					temp = new File(path + tempList[i]);
				} else {
					temp = new File(path + File.separator + tempList[i]);
				}
				if (temp.isFile()) {
					temp.delete();
				}
				if (temp.isDirectory()) {
					delAllFile(path + "/" + tempList[i]);
					delFolder(path + "/" + tempList[i]);
				}
			}
		}
		public static boolean newFile(String filePathAndName, String fileContent) {
			try {
				String filePath = filePathAndName;
				filePath = filePath.toString();
				File myFilePath = new File(filePath);
				if (!myFilePath.exists()) {
					myFilePath.createNewFile();
				}
				FileWriter resultFile = new FileWriter(myFilePath);
				PrintWriter myFile = new PrintWriter(resultFile);
				String strContent = fileContent;
				myFile.println(strContent);
				resultFile.close();
				return true;
			} catch (Exception e) {
				e.printStackTrace();
				return false;
			}
		}
		
		public static float checkSize(String path){
			float allsize=0;
			File f = new File(path);
			if (!f.exists()){
		        return allsize;
			}
			File fa[] = f.listFiles();
			long allsizetemp = 0 ;
			for (int i = 0; i < fa.length; i++) {
				File fs = fa[i];
				if (fs.isDirectory()) {
					
				} else {
					allsizetemp+=fs.length();
				}
			}
			allsize = (float)(Math.round(allsizetemp/1024*100))/100;
			return allsize;
		}
		
		public static String createSmilStr(String src,String mmsconfigurl) {
			
			if("".equals(src)){
				return "";
			}
			if(src.length()<10){
				return "";
			}
			if("".equals(mmsconfigurl)){
				return "";
			}
			
			
			String folderroot=ServletActionContext.getRequest().getRealPath("/");
			folderroot = folderroot.replace("\\", "/");
			
			String folderpath ="smilfile/"+Tools.getDateMonthStr()+"/"+Tools.getNowRandom()+"/";
	    	File folder  = new File(folderroot+folderpath);
	    	if(!folder.exists()){
	    		folder.mkdirs();
	    	}
	    	
	    	//String material_textpic_path = ServletActionContext.getServletContext().getInitParameter("material_textpic_path");
	    	String tempStr = "";
	    	String suffixStr = "";
	    	String filename ="";
	    	String tempone="";
	    	String temponemore="";
	    	String str = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><smil><head><layout>";	    				
			String[] mmswh= mmsconfigurl.split("x");			
			String region="";
			String body="";
			int allheight=0;
			int num=1;
			String[] frames = src.split("≡");
			System.out.println("==========frames.length============="+frames.length);
			for (int i = 0; i < frames.length; i++) {
				
				String frame = Tools.getStringBetween(frames[i], "<DIV", "</DIV>");
				String par=Tools.getStringBetween(frame, "<INPUT value=", " name=");
				body +="<par dur=\""+par+"ms\">";
				
				if(frame.indexOf("url")!=-1){
					String bgpic = Tools.getStringBetween(frame, "url(", ")");
					String suffixStrbg = Tools.getLastStrByLastStr(bgpic, ".");
					String bgfilename = Tools.getNowRandom()+"."+suffixStrbg;
			    	String bgpicfinish=folderroot+folderpath+bgfilename;
			    	Tools.copyFilesString(folderroot+bgpic,bgpicfinish);
			    	
			    	String[] sources =frames[i].split("<DIV");	
			    	List files = new ArrayList();
					for(int j = 2;j<sources.length;j++){	
						sources[j] = Tools.decodeAll(sources[j]);					
						tempStr=Tools.getStringBetween(sources[j], ">", "</DIV>");
						if(tempStr.indexOf("<A") == 0) {
							tempStr = Tools.getStringBetween(tempStr, "href=\"", "\"");
							suffixStr = Tools.getLastStrByLastStr(tempStr, ".");
							filename = Tools.copyFile(folderroot, folderpath, tempStr);
							if ("".equals(filename)) {
								Tools.delFolder(folderroot + folderpath);
								return "";
							}
							//str += "<" + suffixStr + " src=\"" + filename + "\"/>";
							str += "<audio src=\"" + filename + "\"/>";
						}else if(tempStr.indexOf("<IMG") == 0) {
							tempStr = Tools.getStringBetween(tempStr, "\"", "\"");
							files.add(tempStr);
						}else if(tempStr.indexOf("<LABEL") == 0){
							String[] matconcoltxtmore = tempStr.split("\r\n");
							for(int t = 0 ;t<matconcoltxtmore.length;t++){
								String matconcoltxtone = matconcoltxtmore[t];
								String[] matcolarray = matconcoltxtone.split("</LABEL>");
								for(int m =0;m<matcolarray.length;m++){
									if(matcolarray[m].indexOf("textpic")!=-1){
										tempone = Tools.getStringBetween(matcolarray[m], "textpic/", "\"");
										files.add(tempone);				
									}else{											
										tempone = Tools.getStringBetween(matcolarray[m], ">", "</FONT>");
										tempone = Tools.getLastStrByLastStr(tempone, ">");
										files.add(tempone);										
									}					
								}
								files.add("\r\n");
							}
						}else{
							files.add(Tools.decode("≡"+tempStr));
						}
					}
					List giffilename=new ArrayList();
														
					String name="";
					String finishname="";
					
				}else{
					String[] sources =frames[i].split("<DIV");	
					if(frames[i].indexOf("<LABEL")!=-1){
						List files = new ArrayList();
						for(int j = 2;j<sources.length;j++){	
							sources[j] = Tools.decodeAll(sources[j]);					
							tempStr=Tools.getStringBetween(sources[j], ">", "</DIV>");
							if(tempStr.indexOf("<A") == 0) {
								tempStr = Tools.getStringBetween(tempStr, "href=\"", "\"");
								suffixStr = Tools.getLastStrByLastStr(tempStr, ".");
								filename = Tools.copyFile(folderroot, folderpath, tempStr);
								if ("".equals(filename)) {
									Tools.delFolder(folderroot + folderpath);
									return "";
								}
								//str += "<" + suffixStr + " src=\"" + filename + "\"/>";
								str += "<audio src=\"" + filename + "\"/>";
							}else if(tempStr.indexOf("<IMG") == 0) {
								tempStr = Tools.getStringBetween(tempStr, "\"", "\"");
								files.add(tempStr);
							}else if(tempStr.indexOf("<LABEL") == 0){
								String[] matconcoltxtmore = tempStr.split("\r\n");
								for(int t = 0 ;t<matconcoltxtmore.length;t++){
									String matconcoltxtone = matconcoltxtmore[t];
									String[] matcolarray = matconcoltxtone.split("</LABEL>");
									for(int m =0;m<matcolarray.length;m++){
										if(matcolarray[m].indexOf("textpic")!=-1){
											tempone = Tools.getStringBetween(matcolarray[m], "textpic/", "\"");
											files.add(tempone);				
										}else{											
											tempone = Tools.getStringBetween(matcolarray[m], ">", "</FONT>");
											tempone = Tools.getLastStrByLastStr(tempone, ">");
											files.add(tempone);										
										}					
									}
									files.add("\r\n");
								}
							}else{
								files.add(Tools.decode("≡"+tempStr));
							}
						}
						
					}else{
						for(int j = 2;j<sources.length;j++){
							System.out.println("=======sources.length==================="+sources.length);
							sources[j] = Tools.decodeAll(sources[j]);					
							tempStr=Tools.getStringBetween(sources[j], ">", "</DIV>");
							if(tempStr.indexOf("<A") == 0) {
								tempStr = Tools.getStringBetween(tempStr, "href=\"", "\"");
								suffixStr = Tools.getLastStrByLastStr(tempStr, ".");
								filename = Tools.copyFile(folderroot, folderpath, tempStr);
								if ("".equals(filename)) {
									Tools.delFolder(folderroot + folderpath);
									return "";
								}								
								body += "<audio src=\"" + filename + "\"/>";
							}else if(tempStr.indexOf("<IMG") == 0) {
								int wideth=0;
								int height=0;
								tempStr = Tools.getStringBetween(tempStr, "\"", "\"");								
								filename = Tools.copyFile(folderroot, folderpath, tempStr);
								if ("".equals(filename)) {
									Tools.delFolder(folderroot + folderpath);
									return "";
								}
								try {
								File img = new File(folderroot + folderpath+filename);
								Image imgsrc = ImageIO.read(img);
								wideth = imgsrc.getWidth(null);
								height = imgsrc.getHeight(null);
								} catch (Exception e) {
									e.printStackTrace();
								}		
								if(i==0&&j==2){
									region +="<region id=\"Image"+num+"\" left=\"0\" top=\"0\" width=\""+mmswh[1]+"\" height=\""+height+"\" />";
								}else{
									region +="<region id=\"Image"+num+"\" left=\"0\" top=\""+allheight+"\" width=\""+mmswh[1]+"\" height=\""+height+"\" />";
								}
								allheight+=height;
								body += "<img src=\"" + filename + "\" region=\"Image"+num+"\" />";
								num++;
							}else{
								int height=0;
								filename = Tools.getNowRandom()+i+ ".txt";
								System.out.println("=====filename===================="+filename);
								System.out.println("=====filename length===================="+tempStr.length());
								if (Tools.newFile(folderroot + folderpath + filename,Tools.decode(tempStr)) == false) {
									Tools.delFolder(folderroot + folderpath);
									return "";
								}
								height=(Integer.parseInt(mmswh[1])/12)*12;
								if(i==0&&j==2){
									region +="<region id=\"Text"+num+"\" left=\"0\" top=\"0\" width=\""+mmswh[1]+"\" height=\""+height+"\" />";
								}else{
									region +="<region id=\"Text"+num+"\" left=\"0\" top=\""+allheight+"\" width=\""+mmswh[1]+"\" height=\""+height+"\" />";
								}
								allheight+=height;
								body += "<text src=\"" + filename + "\" region=\"Text"+num+"\" />";
								num++;
							}
							
						}
					}
				}	
				body+="</par>";
			}
			
			String rootlayout = "<root-layout width=\""+mmswh[1]+"\" height=\""+allheight+"\" />";
			str+=rootlayout + region + "</layout></head><body>"+body+"</body></smil>";
			String finallStr = Tools.getStringBetween(str, "<body>", "</body>");
			if("".equals(finallStr)){
				return "";
			}
			filename = Tools.getNowRandom() + ".smil";
			if (Tools.newFile(folderroot + folderpath + filename, str) == false) {
				Tools.delFolder(folderroot + folderpath);
				return "";
			}		
			return folderroot + folderpath + filename;
	    
		}
		
		
		
}
